package edu.caltech.cs.techerlink;

import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.jdo.PersistenceManager;
import javax.servlet.http.*;
import com.google.apphosting.api.DeadlineExceededException;

@SuppressWarnings("serial")
public class CourseServlet extends HttpServlet {
	private static final Logger log = Logger
			.getLogger(CourseServlet.class.getName());

	@Override
	public void doPost(HttpServletRequest req, HttpServletResponse resp)
	throws IOException {
		// change newName to whatever the name of the parameter is that holds departments
		String department = req.getParameter("newName");
		int number = 1000;

		PersistenceManager pm = PMF.get().getPersistenceManager();
		try {
			pm.currentTransaction().begin();
			Course course = new Course(department, number);
			pm.makePersistent(course);
			pm.currentTransaction().commit();
			
			log.info("Course " + course.getKey() + " successfully created." + pm.isClosed() + " " + pm);
			log.info("Course " + department + " " + number);
		}
		catch (DeadlineExceededException e) {
			log.warning("Deadline exceeded creating course.");
		}
		catch (Exception e) {
			log.log(Level.SEVERE, "Exception creating course.", e);
		} finally {
			if (pm.currentTransaction().isActive())
				pm.currentTransaction().rollback();
			pm.close();
		}

		resp.sendRedirect("/");
	}
}